import { useQuery, type QueryKey } from "@tanstack/react-query"
import type { SearchParamsOption } from "ky"
import { Ban, CircleCheck, Loader } from "lucide-react"
import { useState, useEffect, type FC } from "react"
import { Button } from "~/components/ui/button";
import dayjs from 'dayjs'
import { produce } from 'immer'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "~/components/ui/table";

import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"


export interface RequestConfig {
  api: string,
  method: 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head',
  description: string,
  search?: SearchParamsOption,
  body?: BodyInit
  json?: any
}

export interface ResponseData {
  contentType: string,
  serach: Record<string, string>,
  body: any,
  message: string
}

interface BranchTestTableProps {
  apis: RequestConfig[]
  call: (params: RequestConfig) => Promise<ResponseData>
}


interface TableRowWrapperProps {
  meta: RequestConfig
  queryFn: BranchTestTableProps['call'],
  onStatus: (loading: boolean, error: boolean, resp?: ResponseData) => void
}
const TableRowWrapper: FC<TableRowWrapperProps> = ({ meta, queryFn, onStatus }) => {
  const { refetch, data, error, isLoading: isFormLoading, isFetching } = useQuery({
    queryKey: [meta.api, meta.method],
    queryFn: () => queryFn(meta)
  })

  useEffect(() => {
    onStatus(isFormLoading || isFetching, !!error, data)
  }, [isFormLoading, isFetching, error, data])

  return <TableRow>
    <TableCell className="px-2 py-2 border-b">
      {(isFormLoading || isFetching) ?
        <Loader className="animate-spin h-4 w-4" />
        :
        error
          ?
          <Ban className="text-red-500 text-sm" />
          :
          <CircleCheck className="text-green-500 text-sm" />}
    </TableCell>
    <TableCell className="px-2 py-2 border-b">
      <span className={`px-2 py-1 rounded text-xs font-mono ${meta.method === 'get' ? 'bg-green-100 text-green-800' :
        meta.method === 'post' ? 'bg-blue-100 text-blue-800' :
          meta.method === 'put' ? 'bg-yellow-100 text-yellow-800' :
            meta.method === 'delete' ? 'bg-red-100 text-red-800' :
              'bg-gray-100 text-gray-800'
        }`}>
        {meta.method.toUpperCase()}
      </span>
    </TableCell>
    <TableCell className="px-2 py-2 border-b font-mono text-xs sm:text-sm">
      <div className="break-all">{meta.api}</div>
    </TableCell>
    <TableCell className="px-2 py-2 border-b text-xs sm:text-sm hidden sm:table-cell">
      <div className="max-w-xs break-words">{meta.description}</div>
    </TableCell>
    <TableCell className="px-2 py-2 border-b">
      <Button
        onClick={() => refetch()}
        disabled={isFormLoading}
        variant={isFormLoading ? "outline" : "default"}
      >
        {isFormLoading ? '测试中...' : '测试'}
      </Button>
    </TableCell>
    <TableCell className="px-2 py-2 border-b text-xs hidden lg:table-cell">
      {data && (
        <div className="max-w-xs">
          <div className="font-semibold text-green-600 flex items-center gap-1">成功</div>
          <div className="text-gray-600 text-xs">
            {dayjs().format('YYYY-MM-DD HH:mm:ss')}
          </div>

        </div>
      )}
      {error && (
        <div className="max-w-xs">
          <div className="font-semibold text-red-600 flex items-center gap-1">失败</div>
          <div className="text-gray-600 text-xs">
            {dayjs().format('YYYY-MM-DD HH:mm:ss')}
          </div>
        </div>
      )}
    </TableCell>
    <TableCell className="px-2 py-2 border-b text-xs hidden lg:table-cell">
      {data && (
        <details className="mt-1">
          <summary className="cursor-pointer text-blue-600 text-xs">查看详情</summary>
          <pre className="mt-1 p-2 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-auto max-h-32">
            {JSON.stringify(data, null, 2)}
          </pre>
        </details>
      )}
      {error && (
        <div className="max-w-xs text-red-500 text-xs break-words">
          <span >{error.message}</span>
        </div>
      )}
    </TableCell>
  </TableRow>
}

export default function BranchTestTable({ apis, call }: BranchTestTableProps) {

  const [isBatchTesting, setIsBatchTesting] = useState(false)
  const [searchTerm, setSearchTerm] = useState('')
  const [methodFilter, setMethodFilter] = useState<string>('all')
  const [tableList, setTableList] = useState<{
    loading: boolean,
    error: boolean,
    resp?: ResponseData
  }[]>(Array.from({ length: apis.length }).map(() => ({
    loading: true,
    error: false,
  })))



  // 过滤接口
  const filteredApis = apis.filter(api => {
    const matchesSearch = api.api.toLowerCase().includes(searchTerm.toLowerCase()) ||
      api.description.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesMethod = methodFilter === 'all' || api.method === methodFilter
    return matchesSearch && matchesMethod
  })

  const total = tableList.length
  const loading = tableList.filter(item => item.loading).length
  const error = tableList.filter(item => item.error).length
  const success = tableList.filter(item => item.resp).length
  const pending = tableList.filter(item => !item.loading && !item.error && !item.resp).length

  return (
    <div>
      <div className="mb-4 flex gap-2 items-center">
        <Button
          disabled={isBatchTesting}
          variant={isBatchTesting ? "outline" : "default"}
          onClick={() => {
            setIsBatchTesting(true)
          }}
        >
          {isBatchTesting ? '批量测试中...' : '批量测试所有接口'}
        </Button>

        {/* 统计信息 */}
        <div className="ml-6 flex gap-4 text-sm">
          <div className="flex items-center gap-2">
            <span className="text-gray-600">总计:</span>
            <span className="font-semibold">{total}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-blue-600">测试中:</span>
            <span className="font-semibold">{loading}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-green-600">成功:</span>
            <span className="font-semibold">{success}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-red-600">失败:</span>
            <span className="font-semibold">{error}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-gray-600">待测试:</span>
            <span className="font-semibold">{pending}</span>
          </div>
        </div>
      </div>

      {/* 搜索和过滤控件 */}
      <div className="mb-4 flex flex-col sm:flex-row gap-4">
        <div className="flex-1">
          <input
            type="text"
            placeholder="搜索接口或描述..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
        <div className="flex gap-2">
          <Select value={methodFilter} onValueChange={(value) => setMethodFilter(value)}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="Select a fruit" />
            </SelectTrigger>
            <SelectContent>
              <SelectGroup>
                <SelectLabel>Fruits</SelectLabel>
                <SelectItem value="all">全部</SelectItem>
                <SelectItem value="get">GET</SelectItem>
                <SelectItem value="post">POST</SelectItem>
                <SelectItem value="put">PUT</SelectItem>
                <SelectItem value="delete">DELETE</SelectItem>
                <SelectItem value="patch">PATCH</SelectItem>
                <SelectItem value="options">OPTIONS</SelectItem>
                <SelectItem value="head">HEAD</SelectItem>
                <SelectItem value="trace">TRACE</SelectItem>
                <SelectItem value="connect">CONNECT</SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select>

        </div>
      </div>

      <div className="overflow-x-auto">
        <Table className="min-w-full ">
          <TableHeader>
            <TableRow >
              <TableHead >状态</TableHead>
              <TableHead >方法</TableHead>
              <TableHead >接口</TableHead>
              <TableHead >描述</TableHead>
              <TableHead >操作</TableHead>
              <TableHead >响应</TableHead>
              <TableHead >详情</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredApis.map((api, index) => {
              const key = `${api.method}-${api.api}-${index}`
              return (
                <TableRowWrapper
                  onStatus={(loading, error, resp) => {
                    setTableList(produce(prev => {
                      prev.splice(index, 1, {
                        loading,
                        error,
                        resp
                      })
                      return prev
                    }))
                  }}
                  key={key} meta={api} queryFn={call} />
              )
            })}
          </TableBody>
        </Table>
      </div>
    </div>
  )
}